<?php

session_start(); // 开启会话

// 引入数据库连接配置
require 'config.php';
require 'Database.php';

// 如果用户未登录，则跳转到登录页面
if (isset($_SESSION['user_id'])) {
    header('Location: index.php'); // 自动跳转
    exit();
}
// require_once 'Database.php';

// ...

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = $_POST['username'];
    $password = $_POST['password'];
    $password = md5($password);
    $database = new Database();
    if ($database->loginUser($username, $password)) {
        // 登录成功，跳转到首页或其他页面
        header('Location: index.php');
        exit();
    } else {
        $error = "用户名或密码错误";
    }
}

// ...

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login</title>
</head>
<link rel="stylesheet" href="styles.css">
<body>
    <div>
    <h2>Login</h2>
    <?php if (isset($error)) : ?>
        <p><?php echo $error; ?></p>
    <?php endif; ?>
    <form method="post">
        <label for="username">用户名:</label>
        <input type="text" id="username" name="username" required><br>
        <label for="password">密码:</label>
        <input type="password" id="password" name="password" required><br>
        <button type="submit">登录</button>
    </form>
    </div>
</body>
</html>
